<template>
  <div class="member-project-management">
    <el-row>
      <el-col :span="24">
        <div class="header">
          <h1>项目管理</h1>
          <h3>{{ projectName }}</h3>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="16">
        <div class="project-description">
          <h2>项目描述</h2>
          <p :class="{ expanded: isDescriptionExpanded }">
            {{ isDescriptionExpanded ? projectDescription : truncatedDescription }}
            <el-button type="text" v-if="projectDescription.length > 100" @click="toggleDescription">
              {{ isDescriptionExpanded ? '收起' : '展开' }}
            </el-button>
          </p>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="22" :offset="1">
        <div class="tasks">
          <h2>我的任务</h2>
          <el-table :data="pagedTasks" stripe style="width: 100%" @row-click="goToTaskDetail">
            <el-table-column label="任务类型" width="200">
              <template #default="scope">
                <div :class="typeClass(scope.row.type)" class="type-box">
                  {{ scope.row.type }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="任务名" width="450"></el-table-column>
            <el-table-column label="任务完成状态" width="300">
              <template #default="scope">
                <span :class="statusClass(scope.row.status)">
                  {{ scope.row.status }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="任务剩余时间" width="150">
              <template #default="scope">
                {{ calculateRemainingTime(scope.row.endTime) }}
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="prev, pager, next"
              :page-size="5"
              :total="filteredTasks.length"
              @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'


const router = useRouter()
const route = useRoute()
const mode = ref(route.params.id)
const currentUser = ref('') // 当前用户姓名

const projectDescription = ref('')
const projectName = ref('')

const isDescriptionExpanded = ref(false)

const truncatedDescription = computed(() => {
  return projectDescription.value.length > 100 ? projectDescription.value.slice(0, 100) + '...' : projectDescription.value
})

const toggleDescription = () => {
  isDescriptionExpanded.value = !isDescriptionExpanded.value
}

const tasks = ref([])

const currentPage = ref(1)

const filteredTasks = computed(() => {
  return tasks.value.filter(task => task.assignedTo === currentUser.value)
})

const pagedTasks = computed(() => {
  const start = (currentPage.value - 1) * 5
  const end = start + 5
  return filteredTasks.value.slice(start, end)
})

const handlePageChange = (page) => {
  currentPage.value = page
}

const calculateRemainingTime = (endTime) => {
  const end = new Date(endTime)
  const now = new Date()
  const diffTime = end - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays > 0 ? `${diffDays} 天` : '已超时'
}

const statusClass = (status) => {
  switch (status) {
    case '正在进行':
      return 'status-in-progress'
    case '已完成':
      return 'status-completed'
    case '超时':
      return 'status-overdue'
    default:
      return ''
  }
}

const typeClass = (type) => {
  switch (type) {
    case '开发':
      return 'type-development'
    case '测试':
      return 'type-testing'
    case '设计':
      return 'type-design'
    default:
      return ''
  }
}

const goToTaskDetail = (task1) => {
  console.log(task1)
  router.push({ name: 'task-detail', query: { task: JSON.stringify(task1) } })
}

const fetchProjectData = async () => {
  try {
    console.log(mode.value)
    const projectResponse = await axios.get('http://localhost:8080/projects/'+mode.value)
    projectDescription.value = projectResponse.data.description
    projectName.value = projectResponse.data.name
    const tasksResponse = await axios.get('http://localhost:8080/tasks/project/'+mode.value)
    tasks.value = tasksResponse.data
    console.log(tasks.value)
  } catch (error) {
    console.error('获取项目数据和任务数据失败:', error)
  }
}

onMounted(() => {
  fetchProjectData()
  currentUser.value = JSON.parse(window.localStorage.getItem('token')).name// 当前用户姓名
})
</script>

<style scoped>
.member-project-management {
  padding: 20px;
}

h1, h2, h3 {
  text-align: left;
  margin: 0;
  font-size: 1.5em;
  color: #333;
}

p {
  text-align: left;
  max-height: 90px;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header {
  margin-bottom: 20px;
}

.project-description {
  margin-bottom: 20px;
}

.expanded {
  white-space: normal;
}

.tasks {
  margin-bottom: 20px;
}

.status-in-progress {
  color: #399BFF;
  border: 1px solid #399BFF;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-completed {
  color: gray;
  border: 1px solid gray;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-overdue {
  color: red;
  border: 1px solid red;
  padding: 2px 8px;
  border-radius: 4px;
}

.type-box {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  font-size: 1em;
  color: white;
  border-radius: 4px;
  font-weight: bold;
}

.type-development {
  background-color: #399BFF;
}

.type-testing {
  background-color: #28a745;
}

.type-design {
  background-color: #17a2b8;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}
</style>
